<template>
  <div class="alert_download">
    <a-alert class="a-alert">
      <template #icon>
        <icon-exclamation-circle />
      </template>
      <div class="alert-item">合同生成后，修改租车费/续租费/换车费/租车押金/违章押金后，不影响已发起签署的合同金额。</div>
    </a-alert>
    <div class="create-contract" v-permission="handContractPermission">
      <a-button type="primary" @click="() => onClick('new')">手动生成电子合同</a-button>
    </div>
    <div class="download-button" v-permission="getPermission('batchdownload')" @click="downLoadAll({ orderCode: orderCode })">
      批量下载
    </div>
  </div>
  <table-index
    :table="tableCompulsory"
    @loadData="loadCompulsoryData"
    @selection-change="selectionChange"
    @pagenationChange="pagenationChange"
  >
    <template #contractStatus="{ record }">
      <div :class="'contract-statusname contract-statusname-' + record.contractStatus">{{ record.contractStatusName }}</div>
      <!-- 生成失败 -->
      <div v-if="record.contractStatus == -1" class="res-button" @click="errorShow(record)">原因</div>

      <!-- 签署中 -->
      <div v-if="record.contractStatus == 2 || record.contractStatus == 3 || record.contractStatus == 8">
        <!-- 承租方 -->
        <div class="status_copys">
          <div>承租方</div>
          <div v-if="record.lesseeSignStatus == 1" class="lessee_sign lessee_sign_status_1">{{ record.lesseeSignStatusName }}</div>
          <div v-if="record.lesseeSignStatus == 2" class="lessee_sign lessee_sign_status_2">{{ record.lesseeSignStatusName }}</div>
          <div class="copy_link" v-permission="getPermission('contractCopySigningLink')" @click="getLesseeSignUrl(record)">
            <img src="@/assets/link.png" />
            <span> 复制合同链接 </span>
          </div>
        </div>
        <!-- 出租方 -->
        <div class="status_copys">
          <div>出租方</div>
          <div v-if="record.hireSignStatus == 1" class="lessee_sign lessee_sign_status_1">{{ record.hireSignStatusName }}</div>
          <div v-if="record.hireSignStatus == 2" class="lessee_sign lessee_sign_status_2">{{ record.hireSignStatusName }}</div>
        </div>
      </div>

      <!-- 作废中 -->
      <div v-if="record.contractStatus == 7">
        <!-- 承租方 -->
        <div class="status_copys">
          <div>承租方</div>
          <div v-if="record.lesseeInvalidedStatus == 1" class="lessee_sign lessee_sign_status_1">{{
            record.lesseeInvalidedStatusName
          }}</div>
          <div v-if="record.lesseeInvalidedStatus == 2" class="lessee_sign lessee_sign_status_2">{{
            record.lesseeInvalidedStatusName
          }}</div>
          <div
            v-if="record.lesseeInvalidedStatus == 1"
            class="copy_link"
            v-permission="getPermission('contractCopyVoidLink')"
            @click="getLesseeSignUrl(record)"
          >
            <img src="@/assets/link.png" />
            <span> 复制作废链接 </span>
          </div>
        </div>
        <!-- 出租方 -->
        <div class="status_copys">
          <div>出租方</div>
          <div v-if="record.hireInvalidedStatus == 1" class="lessee_sign lessee_sign_status_1">{{ record.hireInvalidedStatusName }}</div>
          <div v-if="record.hireInvalidedStatus == 2" class="lessee_sign lessee_sign_status_2">{{ record.hireInvalidedStatusName }}</div>
        </div>
      </div>
    </template>
    <template #lessee="{ record }">
      <div v-if="record.leaseType == 1">{{ record.lesseeCompanyName }}</div>
      <div v-else>{{ record.lesseeName }}</div>
    </template>

    <template #createNode="{ record }">
      <div v-if="record.createWay == 1 && orderType == 1">{{ record.createNode }}</div>
      <div v-else-if="orderType == 2">{{ record.createNode }}</div>
      <div v-else>-</div>
    </template>
    <!-- 长租显示合同属性 -->
    <template #attribute v-if="orderType && orderType == 2">
      <div>合同属性</div>
    </template>
  </table-index>
  <!-- 更换车牌 -->
  <addPhone ref="addphones" @ok="addphoneFn" />
  <!-- 去签署/去作废 -->
  <openLink ref="openlinks" @ok="openlinkFn" />
  <!-- 维护 -->
  <maintenanceContract ref="maintenances" @ok="maintenanceFn" />
  <!-- 完善信息 -->
  <ImproveInformationModal :type="type" :modal-alert="modalAlert" ref="improveInformationRef" @onOk="improveInformationOnOk" />
  <!-- 生成电子合同 -->
  <ViewContractModal v-model:visible="viewVisible" v-model:loading="viewLoading" :order="viewContractInfo" @on-ok="onOk" />
  <!-- 预览pdf -->
  <pdf-viewer
    :url="pdfViewInfo.url"
    :title="pdfViewInfo.title"
    v-model:visible="pdfViewInfo.show"
    @close="Object.assign(pdfViewInfo, { ...PDFDefaultAttr })"
  />
</template>
<script setup lang="ts">
  import ImproveInformationModal from '@/views/order/modals/improve-information-modal.vue'
  import ViewContractModal from '@/views/order/modals/view-contract-modal.vue'
  import clipboard3 from 'vue-clipboard3'
  import addPhone from '@/views/order/short-order/detail/components/add-phone.vue'
  import openLink from '@/views/order/short-order/detail/components/open-link.vue'
  import maintenanceContract from '@/views/order/short-order/detail/components/maintenance-contract.vue'

  import { ref, onMounted, watch, reactive, inject } from 'vue'
  import { useTable } from '@/hooks/table'
  import {
    signRecordAPI,
    contractRecordAPI,
    invalidAPI,
    initiateAPI,
    nullifyAPI,
    determineAPI,
    revokeAPI,
    getLesseeSignUrlAPI,
    getTenantSignUrlAPI,
    createQysContractAPI,
    createContractAPI,
    getShortOrdrDetails,
    getSorderContractInfo,
  } from '@/api/order/sOrder'
  import { getLongOrderDetails, getCzsContractInfo } from '@/api/order/czsOrder'
  import { getDetail, clientupdate } from '@/api/market/clientInfo'
  import { Message, Modal } from '@arco-design/web-vue'
  import request from '@/api/axios.config'
  import useNavigate from '@/hooks/useNavigate'
  import { isMobile } from '@/utils/validate'
  import useUserStore from '@/store/modules/user'
  import { targetStrColor } from '@/utils'

  // pdf预览
  import { PDFDefaultAttr } from '@/components/pdf-viewer/const'
  const pdfViewInfo = reactive({ ...PDFDefaultAttr })

  const { navigateTo } = useNavigate()
  const { toClipboard } = clipboard3()
  const orderCode = ref()
  const copyurl = ref() //复制承租方链接
  const clientData = ref() //企业联系人信息
  const addphones = ref()
  const openlinks = ref()
  const maintenances = ref()
  const selectedRowKeys = ref([])
  const props = defineProps({
    orderId: Number,
    orderType: Number,
    payType: Number,
    contractAttribute: Number,
    permissionPrefix: String,
  })
  const type = ref('person')
  const modalAlert = ref('')
  const viewVisible = ref(false)
  const viewLoading = ref(false)
  const getContractCountShortOrder = inject<any>('getContractCountShortOrder')
  const getContractCountLongOrder = inject<any>('getContractCountLongOrder')
  const handContractPermission = ref('')
  const userStore: any = useUserStore()
  userStore.setEpDetail()

  // 传入的是后缀，拼接前缀+.+后缀
  const getPermission = (permissionSubfix: string) => {
    return props.permissionPrefix + '.' + permissionSubfix
  }

  const selectionChange = (e: any) => {
    selectedRowKeys.value = e
  }

  // 页数选择后清空 复选框
  const pagenationChange = () => {
    selectedRowKeys.value = []
  }
  // 列表里点击失败原因
  const errorShow = (record: any) => {
    if (record.createErrorCode == 1001) {
      // 1. 姓名手机号不匹配时
      toError(record)
    } else {
      // 2. 其他原因（没有前往修改按钮）
      Modal.confirm({
        title: '提示',
        simple: true,
        hideCancel: true,
        okText: '关闭',
        content: record.createErrorReason,
      })
    }
  }
  // 去修改订单
  const toError = (record: any) => {
    Modal.confirm({
      title: '提示',
      simple: true,
      cancelText: '关闭',
      okText: '前往修改',
      content: '请将承租人姓名修改为上次已通过实名认证的姓名，再进行重新生成合同的操作。',
      onOk: () => {
        if (props.orderType == 1) {
          navigateTo(`/short-order/edit/${props.orderId}`, `${record.orderCode}-修改订单`)
        } else {
          navigateTo(`/long-order/edit/${props.orderId}`, `${record.orderCode}-修改订单`)
        }
      },
      onCancel: () => {
        loadCompulsoryData()
      },
    })
  }
  // 批量下载
  const downLoadAll = (record: any) => {
    console.log(record)
    if (selectedRowKeys.value.length) {
      console.log(selectedRowKeys.value)
      if (props.orderType == 1) {
        request
          .post(
            '/svmsContract/butchDownloadContractFile',
            {
              idList: selectedRowKeys.value,
            },
            {
              responseType: 'blob',
            }
          )
          .then((res) => {
            console.log(res)
            fileDownload(res.data, 'all', record)
          })
      } else {
        request
          .post(
            '/svmsContract/butchDownloadContractFile',
            {
              idList: selectedRowKeys.value,
            },
            {
              responseType: 'blob',
            }
          )
          .then((res) => {
            console.log(res)
            fileDownload(res.data, 'all', record)
          })
      }
    } else {
      Message.warning('请勾选需要下载的合同')
    }
  }
  // 文件下载
  const fileDownload = (_res: any, tp: any, record: any) => {
    console.log(record)
    var name = ''
    var blob: any
    if (tp == 'all') {
      // 批量下载
      name = record.orderCode
      blob = new Blob([_res], { type: 'application/zip' })
    }
    if (tp == 'justone') {
      // 单个下载
      name = record.contractTypeName + record.contractNo
      blob = new Blob([_res], { type: 'application/pdf' })
    }
    let downloadElement = document.createElement('a')
    let href = window.URL.createObjectURL(blob) //创建下载的链接
    downloadElement.href = href
    // downloadElement.download = fileName; //下载后文件名
    downloadElement.download = name //下载后文件名
    document.body.appendChild(downloadElement)
    downloadElement.click() //点击下载
    document.body.removeChild(downloadElement) //下载完成移除元素
    window.URL.revokeObjectURL(href) //释放掉blob对象
  }
  // 生成合同
  const contractGet = (record: any) => {
    createQysContractAPI({ id: record.id }).then((res: any) => {
      console.log(res)
      if (res.result.createErrorCode) {
        if (res.result.createErrorCode == 1001) {
          // 生成失败弹窗
          // 1. 姓名手机号不匹配时
          toError(record)
        } else {
          // 生成失败弹窗
          // 2. 其他原因（没有前往修改按钮）
          Modal.confirm({
            title: '提示',
            simple: true,
            hideCancel: true,
            okText: '关闭',
            content: res.result.createErrorReason,
          })
          loadCompulsoryData()
        }
      } else if (res.result.createErrorCode == null) {
        Message.success('操作成功')
        loadCompulsoryData()
      }
    })
  }
  // 数据
  const loadCompulsoryData = () => {
    var param
    if (props.orderType == 1) {
      // 短租
      param = {
        id: props.orderId,
        orderCode: orderCode.value,
        orderType: props.orderType,
        pageNumber: 1,
        pageSize: 1000,
        payType: props.payType,
      }
      tableCompulsory.tableLoading = true
      contractRecordAPI(param)
        .then((res: any) => {
          // order.value = res.result
          const data = res.result //表
          data.forEach((i: any) => {
            if (i.contractStatus == 3 || i.contractStatus == 7 || i.contractStatus == 10) {
              i.disabled = false
            } else {
              i.disabled = true
            }
          })
          tableCompulsory.dataList = data
          if (tableCompulsory.dataList.length) {
            orderCode.value = tableCompulsory.dataList[0].orderCode
          }
        })
        .finally(() => {
          tableCompulsory.tableLoading = false
        })
    } else {
      // 长租
      param = {
        orderId: props.orderId,
        pageNumber: 1,
        pageSize: 1000,
        contractAttribute: props.contractAttribute,
      }

      tableCompulsory.tableLoading = true
      signRecordAPI(param)
        .then((res: any) => {
          // order.value = res.result
          const data = res.result //表
          data.forEach((i: any) => {
            if (i.contractStatus == 3 || i.contractStatus == 7 || i.contractStatus == 10) {
              i.disabled = false
            } else {
              i.disabled = true
            }
          })
          console.log('data', data)
          tableCompulsory.dataList = data
          if (tableCompulsory.dataList.length) {
            orderCode.value = tableCompulsory.dataList[0].orderCode
          }
        })
        .finally(() => {
          tableCompulsory.tableLoading = false
        })
    }
  }
  const tableCompulsory = useTable({
    pagination: false,
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: true,
    },
    columns: [
      // { title: '', slotName: 'selectkey', width: 120, fixed: 'left' },
      { title: '合同编号', dataIndex: 'contractNo', fixed: 'left', width: 240 },
      { title: '创建方式', dataIndex: 'createWayName' },
      { title: '创建节点', dataIndex: 'createNode', slotName: 'createNode' }, //待修改
      {
        title: '合同属性',
        dataIndex: 'contractAttributeName',
        titleSlotName: 'attribute',
        cellStyle: { width: props.orderType == 2 ? 240 : 0 },
      },
      { title: '合同类型', dataIndex: 'contractTypeName' },
      { title: '合同模板名称', dataIndex: 'templateName', width: 240 },
      { title: '归属门店', dataIndex: 'siteName', width: 240 },
      { title: '合同状态', dataIndex: 'endTime', width: 300, slotName: 'contractStatus' },
      { title: '承租方', slotName: 'lessee' },
      { title: '出租方', dataIndex: 'tenantName' },
      { title: '发起人', dataIndex: 'startPersonName' },
      { title: '发起签署时间', dataIndex: 'startTime', width: 200 },
      { title: '发起节点', dataIndex: 'startNode' },
    ],
    tableLoading: false,
    operates: [
      {
        label: '生成电子合同',
        span: 2,
        show: (record: any) =>
          record.contractStatus == -2 &&
          userStore.syncInventory?.userEcontractEnabled === 1 &&
          ((props.orderType == 1 && userStore.syncInventory.userContractServiceType.includes(0)) ||
            (props.orderType == 2 && userStore.syncInventory.userContractServiceType.includes(1))),
        permission: getPermission('contractGet'), //新加按钮权限
        method: (record: any) => {
          console.log(record)
          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '关闭',
            okText: '确认',
            content: '电子合同生成后，修改订单或费用都不会更新此合同内的信息，请确认是否生成？',
            onOk: () => {
              // 一.if企业,有无手机号
              if (record.leaseType == 1) {
                // 企业
                // 查询企业信息(是否包含手机号)
                getDetail({ id: record.lesseeId }).then((res: any) => {
                  clientData.value = res.result
                  if (res.result.mobile && res.result.linkman) {
                    // 1.有企业手机号和联系人姓名
                    contractGet(record)
                  } else {
                    // 2.没有企业手机号, 发起手机号填写弹窗
                    addphones.value.show(record, 'c', clientData.value)
                  }
                })
              } else {
                // 个人
                contractGet(record)
              }
            },
          })
        },
      },
      {
        label: '重新生成',
        show: (record: any) =>
          record.contractStatus == -1 &&
          userStore.syncInventory?.userEcontractEnabled === 1 &&
          ((props.orderType == 1 && userStore.syncInventory.userContractServiceType.includes(0)) ||
            (props.orderType == 2 && userStore.syncInventory.userContractServiceType.includes(1))),
        permission: getPermission('contractAgain'),
        method: (record: any) => {
          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '关闭',
            okText: '确认',
            content: '电子合同生成后，修改订单或费用都不会更新此合同内的信息，请确认是否生成？',
            onOk: () => {
              if (record.createWay === 2) {
                viewContractInfo.value = {
                  ...viewContractInfo.value,
                  ...{ contractId: record.id, contractType: record.contractType, method: 'create' },
                }
                onClick('edit')
              } else {
                contractGet(record)
              }
            },
          })
        },
      },
      {
        // dev-ok
        label: '预览',
        show: (record: any) =>
          record.contractStatus != 9 &&
          record.contractStatus != 10 &&
          record.contractStatus != 11 &&
          record.contractStatus != -1 &&
          record.contractStatus != -2,
        permission: getPermission('contractPreview'),
        method: (record: any) => {
          console.log(record)
          request
            .post(
              '/svmsContract/downloadContractFile',
              {
                id: record.id,
                type: 1,
              },
              {
                responseType: 'blob',
              }
            )
            .then((res) => {
              console.log(res)
              const binaryData = []
              binaryData.push(res.data)
              let url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }))
              window.open(url)
              // Object.assign(pdfViewInfo, {
              //   url,
              //   title: record.contractTypeName + record.contractNo,
              //   show: true,
              // })
            })
        },
      },
      {
        // dev-ok
        label: '无需签署',
        permission: getPermission('contractNoNeedSign'),
        show: (record: any) => record.contractStatus == 1 || record.contractStatus == -1 || record.contractStatus == -2,
        method: (record: any) => {
          console.log(record)
          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '取消',
            okText: '确认',
            content: `请确认当前合同是否无需签署，无需签署的合同将变为无效状态，并且当前合同不会重新生成`,
            onOk: () => {
              invalidAPI({ id: record.id }).then((res: any) => {
                console.log(res)
                Message.success('操作成功')
                loadCompulsoryData()
              })
            },
          })
        },
      },
      {
        // dev-ok
        label: '发起签署',
        permission: getPermission('contractInitiateSigning'),
        show: (record: any) => record.contractStatus == 1,
        method: (record: any) => {
          console.log(record)
          // 一.if企业,有无手机号
          if (record.leaseType == 1) {
            // 企业
            // 查询企业信息(是否包含手机号)
            getDetail({ id: record.lesseeId }).then((res: any) => {
              clientData.value = res.result
              if (res.result.mobile && res.result.linkman) {
                // 1.有企业手机号
                // ①判断余额(接口判断)
                determineAPI({ orderId: props.orderId, orderType: props.orderType }).then((res: any) => {
                  if (res.result.determine) {
                    // 1.足够
                    initiateFn(record)
                  } else {
                    // 2.不够
                    Modal.confirm({
                      title: '提示',
                      simple: true,
                      hideCancel: true,
                      okText: '关闭',
                      content: `账户余额不足，请先联系工作人员充值，再进行操作`,
                    })
                    return false
                  }
                })
              } else {
                // 2.没有企业手机号, 发起手机号填写弹窗
                addphones.value.show(record, 'a', clientData.value)
              }
            })
          } else {
            // 个人
            // 二.判断余额
            determineAPI({ orderId: props.orderId, orderType: props.orderType }).then((res: any) => {
              if (res.result.determine) {
                // 1.足够
                initiateFn(record)
              } else {
                // 2.不够
                Modal.confirm({
                  title: '提示',
                  simple: true,
                  hideCancel: true,
                  okText: '关闭',
                  content: `账户余额不足，请先联系工作人员充值，再进行操作`,
                })
                return false
              }
            })
          }
        },
      },
      {
        // dev-ok
        label: '去签署',
        permission: getPermission('contractGoSigning'),
        show: (record: any) =>
          record.signWay == 1 && record.contractStatus == 2 && record.lesseeSignStatus == 2 && record.hireSignStatus == 1,
        method: (record: any) => {
          console.log(record)
          // 获取并打开第三方链接
          // openlinks.value.show(record)
          getTenantSignUrlAPI({ id: record.id }).then((res: any) => {
            window.open(res.result)
          })
        },
      },
      {
        // dev-ok
        label: '下载',
        permission: getPermission('contractDownload'),
        show: (record: any) => record.contractStatus == 3 || record.contractStatus == 7 || record.contractStatus == 10,
        method: (record: any) => {
          console.log(record)
          if (record.contractStatus == 10) {
            window.open(import.meta.env.VITE_BASE_PATH + `/download/downloadById?fileId=${record.contractFileId}`)
          } else {
            request
              .post(
                '/svmsContract/downloadContractFile',
                {
                  id: record.id,
                  type: 0,
                },
                {
                  responseType: 'blob',
                }
              )
              .then((res) => {
                console.log(res)
                fileDownload(res.data, 'justone', record)
              })
          }
        },
      },
      {
        // dev-ok
        label: '撤回',
        permission: getPermission('contractWithdraw'),
        show: (record: any) => record.contractStatus == 2,
        method: (record: any) => {
          console.log(record)
          if (record.lesseeSignStatus == 1 || record.hireSignStatus == 1) {
            Modal.confirm({
              title: '提示',
              simple: true,
              cancelText: '取消',
              okText: '确认',
              content: `合同撤回后，承租方签署链接失效，无法完成签署，确认撤回吗？`,
              onOk: () => {
                revokeAPI({ id: record.id }).then(() => {
                  Message.success('操作成功')
                  loadCompulsoryData()
                })
              },
            })
          } else if (record.orderStatus == -100 || record.orderStatus == -1000) {
            revokeAPI({ id: record.id }).then(() => {
              Message.success('操作成功')
              loadCompulsoryData()
            })
          }
        },
      },
      {
        label: '发起作废',
        permission: getPermission('contractInitiateCancellation'),
        show: (record: any) => record.contractStatus == 3,
        method: (record: any) => {
          console.log(record)
          // 一.if企业,有无手机号
          if (record.leaseType == 1) {
            // 企业
            // 查询企业信息(是否包含手机号)
            getDetail({ id: record.lesseeId }).then((res: any) => {
              clientData.value = res.result
              if (res.result.mobile && res.result.linkman) {
                // 1.有企业手机号
                nullifyFn(record)
              } else {
                // 2.没有企业手机号, 发起手机号填写弹窗
                addphones.value.show(record, 'b', clientData.value)
              }
            })
          } else {
            nullifyFn(record)
          }
        },
      },
      {
        label: '去作废',
        permission: getPermission('contractToCancel'),
        show: (record: any) =>
          record.signWay == 1 && record.contractStatus == 7 && record.lesseeInvalidedStatus == 2 && record.hireInvalidedStatus == 1,
        method: (record: any) => {
          console.log(record)
          // 获取并打开第三方链接
          // openlinks.value.show(record)
          getTenantSignUrlAPI({ id: record.id }).then((res: any) => {
            window.open(res.result)
          })
        },
      },
      // {
      //   label: '编辑合同附件', //仅长租
      //   permission: getPermission('contractMaintenance'),
      //   show: (record: any) =>
      //     props.orderType == 2 && record.contractAttribute == 2 && (record.contractStatus == 10 || record.contractStatus == 11),
      //   method: (record: any) => {
      //     maintenances.value.show(record, props.orderId)
      //   },
      // },
    ],
  })
  // 发起签署
  const initiateFn = (record: any) => {
    Modal.confirm({
      title: '提示',
      simple: true,
      cancelText: '取消',
      okText: '确认',
      content: `请确认是否要发起合同签署?`,
      onOk: () => {
        // 发起签署接口
        initiateAPI({ id: record.id }).then(() => {
          // 企业/个人 提示不同
          if (record.leaseType == 1) {
            // 企业
            Modal.confirm({
              title: '提示',
              simple: true,
              hideCancel: true,
              okText: '关闭',
              content: `已将合同信息以短信的形式发送至企业联系人手机，并等待签署`,
              onOk: () => {
                loadCompulsoryData()
              },
            })
          } else {
            // 个人
            Modal.confirm({
              title: '提示',
              simple: true,
              hideCancel: true,
              okText: '关闭',
              content: `已将合同信息以短信的形式发送至承租人手机，并等待签署`,
              onOk: () => {
                loadCompulsoryData()
              },
            })
          }
          loadCompulsoryData()
        })
      },
    })
  }
  // 发起作废
  const nullifyFn = (record: any) => {
    Modal.confirm({
      title: '提示',
      simple: true,
      cancelText: '取消',
      okText: '确认',
      content: `合同已完成签署，确认作废吗?`,
      onOk: () => {
        // 发起作废接口
        nullifyAPI({ id: record.id }).then(() => {
          // 企业/个人 提示不同
          if (record.leaseType == 1) {
            // 企业
            Modal.confirm({
              title: '提示',
              simple: true,
              hideCancel: true,
              okText: '关闭',
              content: `已将作废协议以短信形式发送至企业联系人手机，并等待签署`,
              onOk: () => {
                loadCompulsoryData()
              },
            })
          } else {
            // 个人
            Modal.confirm({
              title: '提示',
              simple: true,
              hideCancel: true,
              okText: '关闭',
              content: `已将作废协议以短信形式发送至承租人手机，并等待签署`,
              onOk: () => {
                loadCompulsoryData()
              },
            })
          }
          loadCompulsoryData()
        })
      },
    })
  }
  // 带回电话
  const addphoneFn = (recordData: any) => {
    console.log('recordData-----------', recordData)
    // 补充电话
    if (recordData.type == 'a') {
      // 调用发起签署补充电话的接口(编辑企业客户接口)
      clientupdate({
        id: clientData.value.id,
        clientName: clientData.value.clientName,
        mobile: recordData.phone,
        linkman: recordData.linkman,
      }).then((res: any) => {
        console.log('编辑企业客户接口 ---- 补充电话')
        console.log(res)
        // 判断余额
        determineAPI({ orderId: props.orderId, orderType: props.orderType }).then((res: any) => {
          if (res.result.determine) {
            // 1.足够
            // 发起签署
            initiateFn(recordData.record)
          } else {
            // 2.不够
            Modal.confirm({
              title: '提示',
              simple: true,
              hideCancel: true,
              okText: '关闭',
              content: `账户余额不足，请先联系工作人员充值，再进行操作`,
            })
            return false
          }
        })
      })
    }
    if (recordData.type == 'b') {
      // 调用发起作废补充电话的接口
      clientupdate({
        id: clientData.value.id,
        clientName: clientData.value.clientName,
        mobile: recordData.phone,
        linkman: recordData.linkman,
      }).then((res: any) => {
        console.log('编辑企业客户接口 ---- 补充电话')
        console.log(res)
        // 发起作废
        nullifyFn(recordData.record)
      })
    }
    if (recordData.type == 'c') {
      // 调用生成电子合同补充电话的接口
      clientupdate({
        id: clientData.value.id,
        clientName: clientData.value.clientName,
        mobile: recordData.phone,
        linkman: recordData.linkman,
      }).then((res: any) => {
        console.log('编辑企业客户接口 ---- 补充电话')
        console.log(res)
        // 生成电子合同
        contractGet(recordData.record)
      })
    }
  }
  // 签署弹窗点确定
  const openlinkFn = () => {
    loadCompulsoryData()
  }
  // 上传合同完成
  const maintenanceFn = () => {
    loadCompulsoryData()
  }
  // 快速复制
  const getLesseeSignUrl = (record: any) => {
    getLesseeSignUrlAPI({ id: record.id }).then((res: any) => {
      console.log(res)
      // 复制res.result
      copyurl.value = res.result
      toClipboard(copyurl.value)
      if ([2, 3, 8].includes(Number(record.contractStatus))) {
        Message.success('已将链接复制到剪切板')
      }
      if (record.contractStatus == 7) {
        Message.success('承租方作废链接已复制到剪切板')
      }
    })
  }

  const improveInformationRef = ref()
  const onClick = (typeName: string) => {
    if (typeName === 'new') {
      viewContractInfo.value = {
        ...viewContractInfo.value,
        operationType: 0,
        contractType: 1,
        payType: props.payType,
        contractId: null,
        method: 'create',
      }
    } else {
      viewContractInfo.value = { ...viewContractInfo.value, operationType: 1 }
    }

    console.log('viewContractInfo', viewContractInfo.value)

    if (!isMobile(orderDetails.value.memberPhone)) {
      Message.error('承租人手机号格式不正确，请修改正确后，再生成电子合同')
      return
    } else if (orderDetails.value.orderStatus === 10) {
      Message.error('请先完成订单的排车，再生成电子合同')
      return
    } else if (props.orderType == 1 && !orderDetails.value.carLicenseNo) {
      modalAlert.value = '当前渠道订单的已排车辆未与启程系统的车辆进行匹配，请先完成车辆匹配后，再生成电子合同'
      type.value = 'person'
      improveInformationRef.value.onOpen(orderDetails.value)
      return
    } else if (orderDetails.value.memberType === 1) {
      getDetail({ id: orderDetails.value.clientId }).then((res: any) => {
        const result = res.result
        if (!result.linkman || !result.mobile) {
          modalAlert.value = '请先完善企业联系人信息，再生成电子合同'
          type.value = 'business'
          orderDetails.value = { ...orderDetails.value, ...{ business: result } }
          improveInformationRef.value.onOpen(orderDetails.value)
        } else {
          viewVisible.value = true
        }
      })
      return
    } else {
      viewVisible.value = true
    }
  }

  const improveInformationOnOk = () => {
    getOrdersDetails()
  }

  const onOk = (options: any) => {
    viewLoading.value = true

    const { detail } = options
    createContractAPI({
      orderType: props.orderType,
      orderCode: orderDetails.value.orderCode,
      contractType: 1,
      id: detail?.contractId,
      operationType: detail?.operationType,
      payType: props.payType,
      startCarMileageContract: detail?.isExistenceStartCarMileageFlag ? detail?.startCarMileageContract : null,
      startCarOilContract: detail?.isExistenceStartCarOilFlag ? detail?.startCarOilContract : null,
    })
      .then((res: any) => {
        console.log(res)
        if (res.result.resultErrorCode == 9999) {
          Message.error({
            content: () => targetStrColor(res.result.resultErrorMsg, '公司印章', { color: 'red' }),
          })
        } else if (res.result.createErrorCode) {
          viewVisible.value = false
          if (res.result.createErrorCode == 1001) {
            // 生成失败弹窗
            // 1. 姓名手机号不匹配时
            toError({ orderCode: orderDetails.value.orderCode })
          } else {
            // 生成失败弹窗
            // 2. 其他原因（没有前往修改按钮）
            Modal.confirm({
              title: '提示',
              simple: true,
              hideCancel: true,
              okText: '关闭',
              content: res.result.createErrorReason,
            })
            loadCompulsoryData()
          }
        } else if (res.result.createErrorCode == null) {
          Message.success('操作成功')
          loadCompulsoryData()
          // 参考免费合同
          if (props.orderType == 1) {
            getContractCountShortOrder()
          } else {
            getContractCountLongOrder()
          }
          viewVisible.value = false
        }
      })
      .finally(() => {
        viewLoading.value = false
      })
  }

  watch(
    () => userStore.syncInventory,
    (val: any) => {
      if (val) {
        if (val?.userEcontractEnabled == 1) {
          if (val.userContractServiceType.includes(0) && props.orderType == 1) {
            handContractPermission.value = getPermission('handContract')
          } else if (val.userContractServiceType.includes(1) && props.orderType == 2) {
            handContractPermission.value = getPermission('handContract')
          }
        }
      }
    },
    { immediate: true, deep: true }
  )

  const orderDetails = ref()
  const viewContractInfo = ref()

  const getOrdersDetails = (callback?: Function) => {
    console.log('getOrdersDetails', props.orderType, props.orderType == 1)
    const apiStatus = {
      details: false,
      contracts: false,
    }
    if (props.orderType == 1) {
      getShortOrdrDetails({ id: props.orderId }).then((res: any) => {
        orderCode.value = res.result.orderInfo.orderCode
        orderDetails.value = res.result.orderInfo
        // orderCode.value = 'XC702022111500147'
        if (orderCode.value) {
          loadCompulsoryData()
        }
        apiStatus.details = true
        if (apiStatus.details && apiStatus.contracts) {
          callback && callback()
        }
      })

      getSorderContractInfo({ id: props.orderId }).then((res: any) => {
        const { memberInfoDto } = res.result
        viewContractInfo.value = {
          ...res.result.orderInfo,
          emergencyContactName: memberInfoDto.emergencyContactName,
          emergencyContactPhone: memberInfoDto.emergencyContactPhone,
          payType: props.payType,
        }
        apiStatus.contracts = true
        if (apiStatus.details && apiStatus.contracts) {
          callback && callback()
        }
      })
    } else {
      getLongOrderDetails({ id: props.orderId }).then((res: any) => {
        orderDetails.value = {
          ...res.result.orderInfo,
          carLicenseNo: res.result.orderInfo.licenseNo,
          orderCode: res.result.orderInfo.orderNo,
          startTime: res.result.orderInfo.expectedUseCarTime,
          endTime: res.result.orderInfo.expectedReturnCarTime,
          rentDays: res.result.orderInfo.leaseNumberStr,
          carModelName: res.result.orderInfo.modelName,
          totalAmount: res.result.orderInfo.carRentAmount,
          carDeposit: res.result.orderInfo.carDepositAmount,
          illegalDeposit: res.result.orderInfo.violationDepositAmount,
          orderStatus: res.result.orderInfo.status,
        }
        loadCompulsoryData()
        apiStatus.details = true
        if (apiStatus.details && apiStatus.contracts) {
          callback && callback()
        }
      })

      getCzsContractInfo({ id: props.orderId }).then((res: any) => {
        const { memberInfoDto } = res.result

        viewContractInfo.value = {
          ...res.result.orderInfo,
          carLicenseNo: res.result.orderInfo.licenseNo,
          orderCode: res.result.orderInfo.orderNo,
          startTime: res.result.orderInfo.expectedUseCarTime,
          endTime: res.result.orderInfo.expectedReturnCarTime,
          rentDays: res.result.orderInfo.leaseNumberStr,
          carModelName: res.result.orderInfo.modelName,
          totalAmount: res.result.orderInfo.carRentAmount,
          carDeposit: res.result.orderInfo.carDepositAmount,
          illegalDeposit: res.result.orderInfo.violationDepositAmount,
          orderStatus: res.result.orderInfo.status,
          emergencyContactName: memberInfoDto.emergencyContactName,
          emergencyContactPhone: memberInfoDto.emergencyContactPhone,
          payType: props.payType,
        }
        apiStatus.contracts = true
        if (apiStatus.details && apiStatus.contracts) {
          callback && callback()
        }
      })
    }
  }
  onMounted(() => {
    // 获取企业联系人id
    if (props.orderId) {
      getOrdersDetails(() => {
        // 地址栏传入 triggerNewContract 时，默认打开新合同弹窗
        let triggerNewContract: any = sessionStorage.getItem('triggerNewContract')
        if (triggerNewContract == 82) {
          onClick('new')
          sessionStorage.removeItem('triggerNewContract')
        }
      })
    }
  })
</script>
<style scoped lang="less">
  .alert_download {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 20px;
  }
  .create-contract {
    margin-left: 12px;
  }
  .download-button {
    display: inline-block;
    height: 32px;
    margin-left: 12px;
    line-height: 32px;
    padding: 0 15px;
    font-size: 14px;
    color: #fff;
    background-color: rgb(var(--primary-6));
    border: 1px solid transparent;
    cursor: pointer;
  }
  .res-button {
    display: inline-block;
    margin-top: 4px;
    padding: 0 8px;
    font-size: 12px;
    border-radius: 2px;
    color: #fff;
    background-color: rgb(var(--primary-6));
    border: 1px solid transparent;
    cursor: pointer;
  }
  .status_copys {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-top: 4px;
  }
  .lessee_sign_status_1 {
    color: #ff7d00;
    border: 1px solid #ff7d00;
    background-color: #fff7e8;
    font-size: 12px;
    padding: 0 8px;
    border-radius: 2px;
  }
  .lessee_sign_status_2 {
    color: #00b42a;
    border: 1px solid #00b42a;
    background-color: #e8ffea;
    font-size: 12px;
    padding: 0 8px;
    border-radius: 2px;
  }
  .copy_link {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    color: #3491fa;
    text-decoration: underline;
    cursor: pointer;
    img {
      width: 20px;
      height: 20px;
    }
  }
  .contract-statusname {
    font-size: 14px;
    font-weight: 400;
  }
  .contract-statusname-1 {
    // 未发起
    color: #c7c7c7;
  }
  .contract-statusname-2 {
    // 签署中
    color: #3491fa;
  }
  .contract-statusname-3 {
    // 已完成
    color: #00b42a;
  }
  .contract-statusname-4 {
    // 已撤回
    color: #f53f3f;
  }
  .contract-statusname-5 {
    // 已撤回
    color: #f53f3f;
  }
  .contract-statusname-6 {
    // 已截止
    color: #f53f3f;
  }
  .contract-statusname-7 {
    // 作废中
    color: #ff7d00;
  }
  .contract-statusname-8 {
    // 已作废
    color: #f53f3f;
  }
  .contract-statusname-9 {
    // 无效
    color: #722ed1;
  }
  .contract-statusname--1 {
    // 生成失败
    color: #f53f3f;
  }
  .lessee_sign {
    margin: 0 8px 0;
  }
  .hire_sign {
    margin: 0 8px 0;
  }
  .a-alert {
    font-size: 14px;
    font-weight: 400;
    color: #1d2129;
    flex: 1;
  }
</style>
